﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.MountAndBlade.View.MissionViews.SiegeWeapon.RangedSiegeWeaponViewController
// Assembly: TaleWorlds.MountAndBlade.View, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 61152EB8-513B-4D4A-8AC0-0D1465C6CF6C
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\Modules\Native\bin\Win64_Shipping_Client\TaleWorlds.MountAndBlade.View.dll

using TaleWorlds.DotNet;
using TaleWorlds.Engine;

#nullable disable
namespace TaleWorlds.MountAndBlade.View.MissionViews.SiegeWeapon
{
  [DefaultView]
  public class RangedSiegeWeaponViewController : MissionView
  {
    public override void OnObjectUsed(Agent userAgent, UsableMissionObject usedObject)
    {
      base.OnObjectUsed(userAgent, usedObject);
      if (!userAgent.IsMainAgent || !(usedObject is StandingPoint))
        return;
      UsableMachine machineFromPoint = this.GetUsableMachineFromPoint(usedObject as StandingPoint);
      if (!(machineFromPoint is RangedSiegeWeapon))
        return;
      RangedSiegeWeapon rangedSiegeWeapon = machineFromPoint as RangedSiegeWeapon;
      if (rangedSiegeWeapon.GetComponent<RangedSiegeWeaponView>() != null)
        return;
      this.AddRangedSiegeWeaponView(rangedSiegeWeapon);
    }

    private UsableMachine GetUsableMachineFromPoint(StandingPoint standingPoint)
    {
      GameEntity gameEntity = standingPoint.GameEntity;
      while ((NativeObject) gameEntity != (NativeObject) null && !gameEntity.HasScriptOfType<UsableMachine>())
        gameEntity = gameEntity.Parent;
      if ((NativeObject) gameEntity != (NativeObject) null)
      {
        UsableMachine firstScriptOfType = gameEntity.GetFirstScriptOfType<UsableMachine>();
        if (firstScriptOfType != null)
          return firstScriptOfType;
      }
      return (UsableMachine) null;
    }

    private void AddRangedSiegeWeaponView(RangedSiegeWeapon rangedSiegeWeapon)
    {
      RangedSiegeWeaponView component;
      switch (rangedSiegeWeapon)
      {
        case Trebuchet _:
          component = (RangedSiegeWeaponView) new TrebuchetView();
          break;
        case Mangonel _:
          component = (RangedSiegeWeaponView) new MangonelView();
          break;
        case Ballista _:
          component = (RangedSiegeWeaponView) new BallistaView();
          break;
        default:
          component = new RangedSiegeWeaponView();
          break;
      }
      component.Initialize(rangedSiegeWeapon, this.MissionScreen);
      rangedSiegeWeapon.AddComponent((UsableMissionObjectComponent) component);
    }
  }
}
